<template>
  <div class="purchase-incoming-list" style="height: calc(100vh - 104px); padding: 20px;">
    <div style=" background: #fff; border-radius: 10px; margin-bottom: 10px; padding: 20px 25px 10px;">
      <div class="dashboard-inner">
        付款单报表
        <el-tooltip class="item" effect="dark" content="温馨提示：表格对应列可以通过拖动改变表格宽度" placement="top">
          <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
        </el-tooltip>
      </div>
      <div style="display: flex;">
        <common-operation-form style="margin-top: 6px; flex: 1;" :list="list"/>
        <common-operation-form style="margin-top: 6px;" :marginRight="'0px'" :marginLeft="'6px'" :list="rightList"/>
      </div>
    </div>

    <div style="  height: calc(100% - 90px); background: #fff;" class="settement-right-content " >
      <div v-show="activeName === 'first'" style="width: calc(100% - 50px); margin-left: 25px; margin-right: 25px;">
        <el-table style="margin-top: 15px;" :row-class-name="tableRowClassName" :height="windowHeight - 10" show-summary  :summary-method="getSummaries"
                  @selection-change="handleSelectionChange"
                  v-loading="table.loading" :data="table.data" border ref="purchaseIncomingTableRef">
          <el-table-column
              type="selection" fixed="left" align="center"
              :header-align="`center`"
              width="55">
          </el-table-column>
          <el-table-column
              v-for="(item, index) in table.header1"
              :prop="item.prop"
              :index="index" align="center" :show-overflow-tooltip="true"
              :width="item.width || 'auto'" :header-align="`center`"
              :label="item.label">
            <template slot-scope="scope">
              <span v-if="item.prop === 'createDate'" style=" ">
                {{ parseTime(new Date(scope.row[item.prop]), '{y}-{m}-{d}') }}
              </span>
              <span v-else-if="item.prop === 'audit'" :style="`color: ${scope.row['audit'] ? '#13ce66' : 'red'}`">
                 {{ scope.row['audit'] ? '已审核' : '未审核'}}
              </span>
              <span v-else-if="item.prop === 'profitAndLossInventory'" :style="`color: ${setColor(scope.row['profitAndLossInventory'])}`">
                {{ scope.row['profitAndLossInventory'] }}
              </span>
              <span v-else-if="item.prop === 'productStatus'">
                {{ parseFloat(scope.row['profitAndLossInventory']) > 0 ? '有盈亏' : '无盈亏' }}
              </span>
              <span v-else-if="item.prop === 'inventoryLossAmount'" :style="`color: ${setColor(parseFloat(scope.row['profitAndLossPrice']) < 0 ? scope.row['profitAndLossPrice'] : '0')}`">
                {{ parseFloat(scope.row['profitAndLossPrice']) < 0 ? scope.row['profitAndLossPrice'] : '0' }}
              </span>
              <span v-else-if="item.prop === 'inventorySurplusAmount'" :style="`color: ${setColor(parseFloat(scope.row['profitAndLossPrice']) > 0 ? scope.row['profitAndLossPrice'] : '0')}`">
                {{ parseFloat(scope.row['profitAndLossPrice']) > 0 ? scope.row['profitAndLossPrice'] : '0' }}
              </span>
              <span v-else-if="item.prop === 'type'" :style="`color: ${setColor(scope.row['profitAndLossInventory'])}`">
                  <span v-if="parseFloat(scope.row['profitAndLossInventory']) === 0">
                    无盈亏
                  </span>
                  <el-tag v-else-if="parseFloat(scope.row['profitAndLossInventory']) < 0"
                          type="warning"
                          effect="dark">
                    盘亏
                  </el-tag>
                   <el-tag v-else
                           type="success"
                           effect="dark">
                    盘盈
                  </el-tag>
              </span>
              <span v-else-if="item.prop === 'profitAndLossPrice'" :style="`color: ${setColor(scope.row['profitAndLossPrice'])}`">
                {{ scope.row[item.prop] }}
              </span>
              <span :style="`${scope.row[item.prop] > 0 ? 'color: red; ' : 'color: #000;'}`" v-else-if="item.prop === 'unpaidAmount'">
                 {{scope.row[item.prop]}}
              </span>
              <span v-else style=" ">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column
              label="操作" width="155" fixed="right">
            <template slot-scope="scope">
              <div style="display: flex;">
                <!--                <el-button size="mini" class="minimini" @click="detail(scope.row)" type="primary">确认</el-button>-->
                <el-button size="mini" class="minimini" @click="detail(scope.row)" type="success">打印</el-button>
                <el-button size="mini" class="minimini" @click="detail(scope.row)" type="success">详情</el-button>
                <el-button size="mini" class="minimini" @click="del(scope.row)" type="danger">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>


        <el-pagination style="position: relative; text-align: right; margin-top: 10px;"
                       :current-page="page.pageNumber"
                       layout="sizes, jumper, prev, pager, next" :page-size="page.pageSize"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog style="margin-top: 10px;"
               :close-on-click-modal="false"
               width="95%" v-dialog-drag :modal="false"
               custom-class="dialoginter107"
               :visible.sync="dialog.dialogVisible">
      <span slot="title">
        付款单详情
        <el-tooltip class="item" effect="dark" content="温馨提示：对应列可以通过拖动改变表格宽度" placement="top">
          <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
        </el-tooltip>
      </span>
      <add v-if="dialog.formData && dialog.dialogVisible"
           :formData="dialog.formData"
           style="padding: 15px !important; height: 100% !important; "/>
    </el-dialog>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import CommonDialogForm from "@/components/CommonDialogForm/index.vue";
import {
  deleteInventoryCheckByID, delInventoryCheckByID,
} from "@/api/inventory";
import {getUserInfo} from "@/utils/auth";
import {
  calculateTwoValue,
  deepClone,
  isNotANumberOrEmpty,
  keepTwoDecimalFull,
  parseTime
} from "@/utils";
import { getPurchaseIncoming} from "@/api/purchaseIncoming";
import add from "@/views/accounts-payable/add.vue";
import {audit} from "@/api/accountsPayable";

export default {
  // name: 'purchase_incoming_report',
  components: {CommonOperationForm, CommonDialogForm, add},
  data() {
    return {
      activeName: 'first',
      table: {
        data: [],
        header1: [
          {
            prop: 'createDate',
            label: '单据日期',
            width: '150px',
          },
          {
            prop: 'documentNumber',
            label: '单据编号',
            width: '150px',
          },
          {
            prop: 'supplierName',
            label: '供应商',
          },
          {
            prop: 'totalPayableAmount',
            label: '付款金额',
          },
          {
            prop: 'totalVerificationAmount',
            label: '核销金额',
          },
          {
            prop: 'totalUnverifiedAmount',
            label: '本次预付',
          },
          {
            prop: 'accountName',
            label: '制单人',
          },
          {
            prop: 'audit',
            label: '审核状态',
          },
          {
            prop: 'remarks',
            label: '备注信息',
          }
        ],
        loading: false,
        multipleSelection: [],
      },
      dialog: {
        dialogVisible: false,
        formData: null,
        rowIndex: -1,
      },
      rightList: [
        {
          type: 'button',
          buttonText: '审核',
          buttonType: "primary",
          event: () => {
          }
        },
        {
          type: 'button',
          buttonText: '反审核',
          buttonType: "primary",
          event: () => {
            if (this.table.multipleSelection.length <= 0) {
              this.$message.error("请先勾选择需要删除的单据");
              return;
            }

            let list = this.table.multipleSelection;

            audit({
              auditStatus: false,
              list,
            }).then(res => {
              this.$message.success("操作成功");
              this.page.pageNumber = 1;
              this.getPurchaseIncoming();
            });
            console.log(list);
          }
        },
        {
          type: 'button',
          buttonText: '删除',
          buttonType: "danger",
          event: () => {
            if (this.table.multipleSelection.length <= 0) {
              this.$message.error("请先勾选择需要删除的单据");
              return;
            }

            console.log(this.table.multipleSelection);
            let IDList = [];
            for (let i = 0; i < this.table.multipleSelection.length; i++) {
              let {_id} = this.table.multipleSelection[i];
              IDList.push(_id);
            }
            deleteInventoryCheckByID({IDList}).then(res => {
              console.log(res);
              this.page.pageNumber = 1;
              this.getPurchaseIncoming();
            });
          }
        },
      ],
      list: [
        {
          type: 'input',
          text: '单据编号：',
          inputWidth: '120px',
          width: '70px',
          value: '',
        },
        {
          type: 'supplierSetting',
          text: '供应商：',
          required: false,
          selectWidth: '120px',
          multiple: false,
          value: '',
        },
        {
          text: '结算账户：',
          selectWidth: '160px',
          width: '80px',
          required: false,
          field: 'customerType',
          type: 'settlementAccount',
          defaultSettlementAccount: false,
          value: null,
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-search',
          buttonText: '搜索',
          event: () => {
            this.page.pageNumber = 1;
            this.getPurchaseIncoming();
          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-clear',
          buttonText: '重置',
          event: () => {
            this.page.pageNumber = 1;
            this.list[2].value = "";
            this.list[0].value = "";
            this.list[1].value = "";
            this.getPurchaseIncoming();
          }
        },
      ],
      list2: [
        {
          type: 'input',
          text: '商品名称：',
          width: '70px',
          inputWidth: '120px',
          value: '',
        },
        {
          type: 'input',
          text: '单据编号：',
          width: '70px',
          inputWidth: '120px',
          value: '',
        },
        {
          type: 'warehouse',
          text: '所属仓库：',
          width: '80px',
          selectWidth: '140px',
          multiple: false,
          value: [],
        },
        {
          text: '所属类别：',
          field: 'productCategory',
          requiredMessage: "请选择类别",
          type: 'selectTree',
          width: '70px',
          showMenuButton: false,
          node: null,
          value: null,
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-search',
          buttonText: '搜索',
          event: () => {

          }
        },
      ],
      page: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
      },
    }
  },
  activated() {
    console.log("activated");
    this.page.pageNumber = 1;
    this.getPurchaseIncoming();
  },
  mounted() {
    console.log("mounted");
    this.page.pageNumber = 1;
    this.getPurchaseIncoming();
  },
  methods: {
    parseTime,
    documentCopy(text) {
      let textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      this.$message.success("单据编号复制成功");
    },
    paymentStatus(row) {
      let {unpaidAmount} = row;
      return unpaidAmount <= 0; // 结清 true 未结清 false
    },
    detail(row, index) {
      console.log(row);
      this.dialog.dialogVisible = true;
      this.dialog.formData = deepClone(row);
      this.dialog.rowIndex = index;
      this.$refs.purchaseIncomingTableRef?.doLayout();
    },
    del(item) {
      console.log("delete: ", item);
      this.$confirm('删除后将操作商品库存,请再次确定?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        delInventoryCheckByID({
          _id: item._id,
          inventoryCheckData: item.inventoryCheckData,
        }).then(res => {
          this.$message.success("操作成功");
          this.getPurchaseIncoming();
        });
      }).catch(() => {

      });
    },
    handleSelectionChange(val) {
      this.table.multipleSelection = val;
    },
    tableRowClassName({row, rowIndex}) {
      console.log(rowIndex, this.dialog.rowIndex);
      if (rowIndex === this.dialog.rowIndex) {
        return 'highlight';
      }
      return '';
    },
    setPurchaseIncomingData(data) {
      console.log(data);
      // 审核相关操作后不关闭弹出框
      // this.dialog.dialogVisible = false;
      this.dialog.formData = data;
      let { productInfo } = data;
      this.table.data[this.dialog.rowIndex] = data;
      this.table.data = [...this.table.data];
      let info = "";
      for (let j = 0; j < productInfo.length; j++) {
        const ppi = productInfo[j];
        info += ppi.productName;
        info += "(";
        info += ppi.inventory;
        info += "：";
        info += ppi.price;
        info += ")";
        if (j !== productInfo.length - 1) {
          info += ",";
        }
      }

      data['info'] = info;
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      let totalPayableAmount2 = 0.0;
      let totalVerificationAmount2 = 0.0;
      let totalUnverifiedAmount2 = 0.0;
      for (let i = 0; i < data.length; i++) {
        let {totalPayableAmount, totalVerificationAmount, totalUnverifiedAmount} = data[i];
        console.log(data[i])
        if (!isNotANumberOrEmpty(totalPayableAmount))
          totalPayableAmount2 = calculateTwoValue(totalPayableAmount2, totalPayableAmount, 'add');
        if (!isNotANumberOrEmpty(totalVerificationAmount))
          totalVerificationAmount2 = calculateTwoValue(totalVerificationAmount2, totalVerificationAmount, 'add');
        if (!isNotANumberOrEmpty(totalUnverifiedAmount))
          totalUnverifiedAmount2 = calculateTwoValue(totalUnverifiedAmount2, totalUnverifiedAmount, 'add');
      }

      console.log("totalPayableAmount2:", totalPayableAmount2, totalVerificationAmount2, totalUnverifiedAmount2)
      columns.forEach((column, index) => {
        let {label} = column;
        if (label === '付款金额') {
          sums[index] = `${keepTwoDecimalFull(totalPayableAmount2)}`;
        } else if (label === '核销金额') {
          sums[index] = `${keepTwoDecimalFull(totalVerificationAmount2)}`;
        } else if (label === '本次预付') {
          sums[index] = `${keepTwoDecimalFull(totalUnverifiedAmount2)}`;
        } else {
          sums[index] = '';
        }
      });
      this.$nextTick(() => {
        this.$refs.purchaseIncomingTableRef.doLayout();
      })
      console.log(sums);
      return sums;
    },
    getSummaries2(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        sums[index] = '';
      });

      let totalPurchaseInventory = 0;
      let totalPurchasePrice = 0;
      let totalPurchaseTotalAmount = 0;
      for (let i = 0; i < data.length; i++) {
        let {price, inventory, totalAmount} = data[i];
        price = parseFloat(price);
        totalAmount = parseFloat(totalAmount);
        totalPurchasePrice += price;
        totalPurchaseInventory += inventory;
        totalPurchaseTotalAmount += totalAmount;
      }

      sums[7] = totalPurchaseInventory;
      sums[8] = totalPurchasePrice;
      sums[9] = totalPurchaseTotalAmount;
      this.$nextTick(() => {
        this.$refs.purchaseIncomingTableRef?.doLayout();
      });
      return sums;
    },
    setColor(v) {
      v = parseFloat(v);
      if (v > 0) {
        return '#13ce66';
      } else if (v === 0) {
        return '';
      } else {
        return '#ffba00';
      }
    },
    getPurchaseIncoming() {
      this.table.loading = true;
      getPurchaseIncoming({
        userID: getUserInfo().userID,
        typeNameList: ["付款单"],
        documentNumber: this.list[0].value,
        settlementAccountID: this.list[2].value,
        supplierID: this.list[1].value,
      }).then(res => {
        console.log(res);
        this.page.total = res.data.page.totalDocuments;
        this.table.data = res.data.data;
        this.$nextTick(() => {
          this.table.loading = false;
        });
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}


.dashboard-inner {
  font-size: 16px;
  font-weight: 700;
  padding: 0 0 10px 0;
  color: #2f3745;
}

.settement-right-content {
  line-height: 16px;
  flex-wrap: wrap;
  width: 100%;
  border-radius: 10px;
  padding-top: 10px;
  margin-top: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}

</style>

<style>
.purchase-incoming-list .el-table .el-table__footer-wrapper .cell{
  font-weight: 600;
  color: red;
}

.purchase-incoming-list .el-table .highlight {
  background: #f0f9eb;
}

.purchase-incoming-list .el-tabs__header {
  margin-bottom: 8px;
}
</style>
